import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '../../../../auth';

// 检查用户是否有权限访问项目
async function checkProjectAccess(userId: string, projectId: string) {
  const projectUser = await prisma.projectUser.findUnique({
    where: {
      userId_projectId: {
        userId,
        projectId,
      },
    },
  });
  
  return !!projectUser;
}

// POST /api/tasks - 创建任务
export async function POST(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const body = await request.json();

    // 验证请求数据
    const { title, description, status, priority, projectId, assigneeId, dueDate } = body;
    
    if (!title) {
      return NextResponse.json({ error: '任务标题是必填的' }, { status: 400 });
    }
    
    if (!projectId) {
      return NextResponse.json({ error: '项目ID是必填的' }, { status: 400 });
    }

    // 验证用户是否有权限在该项目中创建任务
    const hasAccess = await checkProjectAccess(userId, projectId);
    if (!hasAccess) {
      return NextResponse.json({ error: '没有权限在此项目中创建任务' }, { status: 403 });
    }

    // 验证项目是否存在
    const project = await prisma.project.findUnique({
      where: { id: projectId },
    });

    if (!project) {
      return NextResponse.json({ error: '找不到项目' }, { status: 404 });
    }

    // 如果提供了assigneeId，验证该用户是否为项目成员
    if (assigneeId) {
      const isMember = await prisma.projectUser.findUnique({
        where: {
          userId_projectId: {
            userId: assigneeId,
            projectId,
          },
        },
      });

      if (!isMember) {
        return NextResponse.json({ error: '分配的用户不是项目成员' }, { status: 400 });
      }
    }

    // 创建任务
    const task = await prisma.$transaction(async (tx) => {
      // 创建任务
      const newTask = await tx.task.create({
        data: {
          title,
          description,
          status: status || 'TODO',
          priority: priority || 'MEDIUM',
          projectId,
          assigneeId,
          dueDate: dueDate ? new Date(dueDate) : undefined,
        },
      });

      // 创建活动记录
      await tx.activity.create({
        data: {
          userId,
          type: 'task_created',
          entityId: newTask.id,
          data: { 
            taskTitle: title,
            projectId
          }
        }
      });

      // 如果有分配的用户且不是创建者本人，创建通知
      if (assigneeId && assigneeId !== userId) {
        const notification = await tx.notification.create({
          data: {
            type: 'TASK_ASSIGNED',
            title: '新任务分配',
            content: `您被分配了一个新任务: ${title}`
          }
        });

        // 创建通知接收者关系
        await tx.notificationRecipient.create({
          data: {
            userId: assigneeId,
            notificationId: notification.id
          }
        });
      }

      return newTask;
    });

    return NextResponse.json(task, { status: 201 });
  } catch (error) {
    console.error('创建任务失败:', error);
    return NextResponse.json(
      { error: '创建任务时出错' },
      { status: 500 }
    );
  }
} 